<template>
  <div id="knowManageDiv">
    <Breadcrumb content="知识库维护" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="25">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findKnowledgeList" @keyup="keyupEnter" @search-click="findKnowledgeList"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="tloading" @click="findKnowledgeList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addKnowledgeDialog()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteKnowledge"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <vxe-table ref="knowledgeTableRef" class="mytable-scrollbar knowledgeTableClazz" border="inner" align="center" height="auto" :data="knowledgeList" :loading="tloading" @current-change="knowledgeRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30"></vxe-column>
              <vxe-column field="code" title="编号" width="80">
              </vxe-column>
              <vxe-column field="name" title="名称">
              </vxe-column>
              <vxe-column field="status" title="是否启用" width="60">
                <template #default="{ row }">
                  <el-tag :type="getStatusTagType(row)">{{ getStatusDesc(row) }}</el-tag>
                </template>
              </vxe-column>
              <vxe-column field="seq" title="顺序" width="60">
              </vxe-column>
            </vxe-table>
            <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']" @page-change="handleSizeChange($event)"></vxe-pager>
          </div>
        </Pane>
        <Pane size="75">
          <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
            <el-tab-pane label="基础信息" name="first">
              <el-form ref="knowledgeFormRef" :model="knowledgeForm" :rules="knowledgeFormRule" class="form-input-m" label-width="100px" inline-message>
                <el-row>
                  <el-scrollbar style="height: 100%;width: 100%;">
                    <el-col :span="24">
                      <el-form-item prop="code" label="编码">
                        <el-input type="text" v-model="knowledgeForm.code" placeholder="请输入编码" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item prop="name" label="名称">
                        <el-input type="text" v-model="knowledgeForm.name" placeholder="请输入名称	" clearable></el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="24">
                      <el-form-item label="是否启用" prop="status">
                        <el-switch v-model="knowledgeForm.status" inline-prompt active-text="是" inactive-text="否"></el-switch>
                      </el-form-item>
                    </el-col>

                    <el-col :span="24">
                      <el-form-item prop="remark" label="备注">
                        <el-input type="textarea" v-model="knowledgeForm.remark" placeholder="请输入备注" style="width: 20%;"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item prop="seq" label="顺序">
                        <el-input-number v-model="knowledgeForm.seq" :min="1" :max="1000" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="样本图片">
                        <el-upload class="avatar-uploader" :show-file-list="false" :on-change="uploadChange" :on-success="handleAvatarSuccess" :action="uploadUrl" list-type="picture-card" :auto-upload="false" :before-upload="handlePictureCardPreview" :data="pictureParam" ref="upload">
                          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                          <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                          </el-icon>
                        </el-upload>
                      </el-form-item>
                      <!-- <el-dialog v-model="showPictureDialog" :modal-append-to-body="false" :append-to-body="true">
                      <img width="100%" :src="dialogImageUrl" alt />
                    </el-dialog> -->
                    </el-col>

                    <el-col :span="24">
                      <el-form-item class="form-footer">
                        <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :loading="svloading" @click="saveKnowledge('knowledgeFormRef')"></vxe-button>
                        <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="重置" @click="resetForm('knowledgeFormRef')"></vxe-button>
                      </el-form-item>
                    </el-col>
                  </el-scrollbar>
                </el-row>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="目录" name="second" :disabled="isEmpty(knowledgeForm.id)">
              <KnowledgeCatalogManage ref="catalogManageRef" />
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { AppStore } from '@/stores/store';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { isEmpty } from 'lodash';
import KnowledgeCatalogManage from './KnowledgeCatalogManage.vue'; //失控记录图表
import { Plus } from '@element-plus/icons-vue';

let imageUrl = ref('');

let store = AppStore();

// 全局变量定义区 ==========
// 根据质控规则的关键字查询
let searchForm = {
  searchValue: ''
};
let tloading = ref(false); //加载状态
let svloading = ref(false);
let knowledgeList: any = reactive([]); //质控规则列表表格
let activeName = ref('first');
let catalogManageRef: any = ref(null);
let sltKnowledge: any = {};

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

// 右侧基本信息表单
let knowledgeForm = reactive({
  id: null,
  name: '',
  code: '',
  image: '',
  seq: 1,
  remark: '',
  orgId: '',
  status: true,
  imageName: ''
});

// 右侧基本信息表单检验
let knowledgeFormRule = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

let resetState = ref(true);

const uploadUrl = ref((window as any).apiUrl.VITE_SERVER_URL + '/api/wk/wkKnowledge/uploadKnowledgeImg');
let getImagePath = ref((window as any).apiUrl.VITE_SERVER_URL + '/image/');
const pictureParam = reactive({
  id: '' // 当前知识库id
});

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  findKnowledgeList(); // 获取质控规则表格数据
});

function tabHandleClick(tab) {
  if (tab.index == 1) {
    catalogManageRef.value.initPage(knowledgeForm);
  }
}
// 获取质控规则表格数据
function findKnowledgeList() {
  tloading.value = true;
  knowledgeList.length = 0; //放入数据前清空数据
  imageUrl.value = '';
  const url = '/api/wk/wkKnowledge/findKnowledgePageList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: searchForm.searchValue, pageIndex: page.currentPage, pageSize: page.pageSize }
    })
    .then((res: any) => {
      knowledgeList.push(...res.data.records);
      page.totalResult = res.data.total;
      tloading.value = false;
      const kn = knowledgeList.find((k) => k.id == sltKnowledge.id);
      if (isEmpty(kn)) {
        knowledgeRowClick({ row: knowledgeList[0] }); //默认选中第一条数据
      } else {
        knowledgeRowClick({ row: kn }); //默认选中第一条数据
      }
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function saveKnowledge(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    svloading.value = true;
    if (knowledgeForm.id === null) {
      const url = '/api/wk/wkKnowledge/addKnowledge';
      const knowledge = {
        name: knowledgeForm.name,
        code: knowledgeForm.code,
        image: knowledgeForm.image,
        remark: knowledgeForm.remark,
        status: knowledgeForm.status,
        seq: knowledgeForm.seq,
        orgId: store.userInfo.orgId
      };
      proxy.$http
        .post(url, knowledge)
        .then((res: any) => {
          pictureParam.id = res.data.id;
          const temp: any = proxy.$refs['upload'];
          temp.submit();
          clearForm();
          findKnowledgeList();
          svloading.value = false;
          VxeMessage('新增成功', VxeNotifyType.success);
        })
        .catch((err: any) => {
          svloading.value = false;

          VxeMessage('新增失败', VxeNotifyType.error);
        });
    } else {
      resetState.value = true;
      // 修改用户
      const url = '/api/wk/wkKnowledge/editKnowledge';
      const knowledge = {
        id: knowledgeForm.id,
        name: knowledgeForm.name,
        code: knowledgeForm.code,
        image: knowledgeForm.image,
        remark: knowledgeForm.remark,
        status: knowledgeForm.status,
        seq: knowledgeForm.seq,
        orgId: knowledgeForm.orgId
      };
      proxy.$http
        .post(url, knowledge)
        .then((res: any) => {
          VxeMessage('修改成功', VxeNotifyType.success);
          pictureParam.id = res.data.id;
          const temp: any = proxy.$refs['upload'];
          temp.submit();
          clearForm();
          svloading.value = false;
          setTimeout(() => {
            if (resetState.value) {
              findKnowledgeList();
            }
          }, 300);
        })
        .catch((err: any) => {
          VxeMessage('修改失败', VxeNotifyType.error);
          svloading.value = false;
        });
    }
  });
}

function deleteKnowledge() {
  const sltKnowledges = (proxy.$refs.knowledgeTableRef as any).getCheckboxRecords();
  if (!(sltKnowledges.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delKnowledgeList = sltKnowledges.filter((p: any) => !isEmpty(p.id));
        if (delKnowledgeList.length > 0) {
          const data = { knowledgeList: delKnowledgeList };
          const url = '/api/wk/wkKnowledge/batchDeleteKnowledgeList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findKnowledgeList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeKnowledgeList = sltKnowledges.filter((p: any) => isEmpty(p.id));
        if (removeKnowledgeList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.knowledgeTableRef;
          if ($Xtable) {
            for (const removeRow of removeKnowledgeList) {
              knowledgeList.splice(removeRow.seq - 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findKnowledgeList();
  }
}

//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findKnowledgeList();
}

// 点击设计模式表格当前行触发右侧表单变化
function knowledgeRowClick({ row }: any) {
  if (isEmpty(row)) {
    clearForm();
  } else {
    (proxy.$refs.knowledgeTableRef as any).setCurrentRow(row);
    setKnowledgeForm(row);
    if (activeName.value == 'second') {
      catalogManageRef.value.initPage(knowledgeForm);
    }
  }
}

// 新建
function addKnowledgeDialog() {
  clearForm();
  (proxy.$refs.knowledgeTableRef as any).clearCurrentRow();
  activeName.value = 'first';
}

// 清空中间规则弹框表单
function clearForm() {
  knowledgeForm.id = null;
  knowledgeForm.name = '';
  knowledgeForm.code = '';
  knowledgeForm.image = '';
  knowledgeForm.seq = page.totalResult + 1;
  knowledgeForm.remark = '';
  knowledgeForm.orgId = '';
  knowledgeForm.status = true;
  imageUrl.value = '';
  knowledgeForm.imageName = '';
}

function resetForm() {
  knowledgeForm.name = '';
  knowledgeForm.code = '';
  knowledgeForm.image = '';
  knowledgeForm.seq = page.totalResult + 1;
  knowledgeForm.remark = '';
  knowledgeForm.orgId = '';
  knowledgeForm.status = true;
  imageUrl.value = '';
  knowledgeForm.imageName = '';
}

function setKnowledgeForm(row: any) {
  knowledgeForm.id = row.id;
  knowledgeForm.name = row.name;
  knowledgeForm.code = row.code;
  knowledgeForm.image = row.image;
  knowledgeForm.seq = row.seq;
  knowledgeForm.remark = row.remark;
  knowledgeForm.orgId = row.orgId;
  knowledgeForm.status = row.status;
  knowledgeForm.imageName = row.imageName;
  imageUrl.value = getImagePath.value + knowledgeForm.imageName;
  sltKnowledge = row;
}

// 获取是否静态的tag标记(绿/红)
function getStatusTagType(row: any) {
  if (row.status) {
    return 'success';
  } else {
    return 'danger';
  }
}

// 获取是否静态文字(是/否)
function getStatusDesc(row: any) {
  if (row.status) {
    return '是';
  } else {
    return '否';
  }
}

function handlePictureCardPreview(file) {}

function handleAvatarSuccess(response, uploadFile) {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  findKnowledgeList();
  resetState.value = false;
}

function uploadChange(uploadFile, uploadFiles) {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
}
</script>

<style lang="scss" scoped>
#knowManageDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBody {
        height: calc(100% - 40px - 32px);
      }
      .el-tabs {
        height: 100%;
        :deep(.el-tabs__content) {
          height: calc(100% - 40px);
          padding: 0;
          .el-tab-pane {
            height: 100%;
          }
          #pane-first {
            padding: 15px;
            height: calc(100% - 30px);
            .el-form {
              height: 100%;
              .el-row {
                height: 100%;
              }
            }
          }
        }
      }
    }
  }
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
